const express = require("express");
const router = express.Router();
const ManagerModel = require("../../model/ManagerModel");
const md5 = require("md5")
// const getUnix = require("../../model/tools")

router.get("/", async (req, res) => {

    // 获取管理员数据
    let result = await ManagerModel.find({})
    res.render("admin/manager/index.html", {
        list: result
    })
})

router.get("/add", (req, res) => {

    res.render("admin/manager/add.html")
})

router.post("/doAdd", async (req, res) => {

    // 获取表单传过来的数据
    let username = req.body.username
    let password = req.body.password
    let repassword = req.body.repassword
    let email = req.body.email
    let mobile = req.body.mobile

    // 验证数据合法性
    if (!username) {
        res.render("admin/public/error.html", {
            "redirectUrl": `/${req.app.locals.adminPath}/manager/add`,
            "message": "用户名不能为空"
        })
        return false
    }

    if (password.length < 6) {
        res.render("admin/public/error.html", {
            "redirectUrl": `/${req.app.locals.adminPath}/manager/add`,
            "message": "密码长度不能小于6位数"
        })
        return false
    }

    if (password !== repassword) {
        res.render("admin/public/error.html", {
            "redirectUrl": `/${req.app.locals.adminPath}/manager/add`,
            "message": "两次密码不一致"
        })
        return false
    }

    // 判断数据库有没有需要增加的数据，数据库验证
    let result = await ManagerModel.find({
        "username": username,
    })

    if (result.length) {
        res.render("admin/public/error.html", {
            "redirectUrl": `/${req.app.locals.adminPath}/manager/add`,
            "message": "已存在该用户，请重新注册"
        })
    } else {
        // 执行增加操作
        let addResult = new ManagerModel({
            username,
            password: md5(password),
            email,
            mobile,
            addtime: new Date().getTime()
        })

        await addResult.save()

        res.redirect(`/${req.app.locals.adminPath}/manager`)
    }
})

router.get("/edit", async (req, res) => {
    let id = req.query.id
    let result = await ManagerModel.find({"_id": id})
    if (result.length) {
        res.render("admin/manager/edit.html", {
            list: result[0],
            id: id
        })
    } else {
        res.redirect(`/${req.app.locals.adminPath}/manager`)
    }
    
})


router.post("/doEdit", async (req, res) => {
    let id = req.body.id

    let password = req.body.password
    let repassword = req.body.repassword
    let mobile = req.body.mobile
    let email = req.body.email
    let status = req.body.status
    
   
    if (password.length) {  // 要修改密码的情况下
        if (password.length < 6) {
            res.render('admin/public/error', {
                "message": '密码长度不能小于6位数',
                "redirectUrl": `/${req.app.locals.adminPath}/manager/edit?id=${id}`
            })
            return
        }
        if (password != repassword) {
            res.render('admin/public/error', {
                "message": '两次密码不一致',
                "redirectUrl": `/${req.app.locals.adminPath}/manager/edit?id=${id}`
            })
        }
        let result = await ManagerModel.updateOne({"_id": id}, {
            email,
            mobile,
            'password': md5(password),
            status
        })
        if (result) {
            res.render("admin/public/success.html", {
                "redirectUrl": `/${req.app.locals.adminPath}/manager`,
                "message": "修改成功"
            })
        } else {
            res.render("admin/public/error.html", {
                "redirectUrl": `/${req.app.locals.adminPath}/manager`,
                "message": "修改失败"
            })
        }
    } else {    // 不修改密码，只修改其他信息
        let result = await ManagerModel.updateOne({"_id": id}, {
            mobile,
            email,
            status
        }, function(err, docs) {
            if (err) {
                console.log(err);
            } else {
                console.log("updated docs: ", docs);
            }
        })
        if (result) {
            res.render("admin/public/success.html", {
                "redirectUrl": `/${req.app.locals.adminPath}/manager`,
                "message": "修改成功"
            })
        } else {
            res.render("admin/public/error.html", {
                "redirectUrl": `/${req.app.locals.adminPath}/manager`,
                "message": "修改失败"
            })
        }
    }
    
})

router.get("/delete", async (req, res) => {
    let id = req.query.id
    let result = await ManagerModel.deleteOne({"_id": id})
    res.render('admin/public/success.html', {
        message: '删除成功',
        redirectUrl: `/${req.app.locals.adminPath}/manager`
    })
})

module.exports = router